package com.tengju.user.application.archives;

import com.tengju.data.domain.model.clickhouse.OdsBigdataStarIndicatorStatRepository;
import com.tengju.data.domain.model.user.StarIndicator;
import com.tengju.data.domain.shared.DateUtil;
import com.tengju.support.domain.model.sms.SmsKey;
import com.tengju.support.domain.model.sms.SmsRecordRepository;
import com.tengju.user.application.shared.ApplicationException;
import com.tengju.user.application.sms.SmsBizService;
import com.tengju.user.domain.model.user.UserIdCode;
import com.tengju.user.domain.model.user.UserInfo;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDate;
import java.util.List;

import static com.tengju.user.application.shared.ApplicationExceptionCode.*;
import static com.tengju.user.domain.model.star.StarIndicatorType.CUSTOMER_MEMBERS_NUM;
import static com.tengju.user.domain.model.star.StarIndicatorType.DEVELOP_DEALER_NUM;

/**
 * @author chenhang
 * @Date 2021/11/15
 */
@Service
@RequiredArgsConstructor(onConstructor_ = {@Autowired})
@Slf4j
public class StarUpcomingService {

    private final OdsBigdataStarIndicatorStatRepository odsBigdataStarIndicatorStatRepository;
    private final SmsRecordRepository smsRecordRepository;
    private final SmsBizService smsBizService;

    @Transactional(value = "dealerTransactionManager", rollbackFor = Exception.class)
    public void sendSmsStarUpcoming(UserIdCode userIdCode, UserInfo userInfo) {
        try {
            boolean isExist = smsRecordRepository.existRecord(userIdCode.getValue(), SmsKey.UPCOMING_NOTICE);
            if (isExist) {
                log.info("即将晋升短信已发送，idCode:{},不重复推送！",userIdCode.getValue());
                return;
            }
            if (userInfo == null || StringUtils.isEmpty(userInfo.getWholePhoneNumber())) {
                log.error("即将晋升短信异常，用户：{} 不存在或手机号不存在",userIdCode.getValue());
                throw ApplicationException.error(UPCOMING_NO_USER, userIdCode.getValue());
            }
            String mobile = userInfo.getWholePhoneNumber();
            smsRecordRepository.save(userIdCode.getValue(), SmsKey.UPCOMING_NOTICE);

            int lackNum = 0;
            String lackName = "经销商";
            LocalDate now = LocalDate.now();
            int dayInt = DateUtil.formatDayInt(now);
            List<StarIndicator> starIndicators = odsBigdataStarIndicatorStatRepository.batchQueryByIdCodeAndDate(userIdCode.getValue(),dayInt);
            for (StarIndicator starIndicator : starIndicators) {
                if (!(starIndicator.getStarIndicatorType().equals(DEVELOP_DEALER_NUM) ||
                        starIndicator.getStarIndicatorType().equals(CUSTOMER_MEMBERS_NUM))) {
                    continue;
                }
                if (starIndicator.isMeetTarget()) {
                    continue;
                }
                if (starIndicator.getStarIndicatorType().equals(DEVELOP_DEALER_NUM)) {
                    lackName = "经销商";
                } else {
                    lackName = "客户";
                }
                lackNum = starIndicator.getIndicatorTargetValue().subtract(starIndicator.getIndicatorValue()).intValue();
            }
            if (lackNum <= 0) {
                log.error("即将晋升短信异常，用户：{} 指标数据异常,{},{}", userIdCode.getValue(), lackName, lackNum);
                throw ApplicationException.error(UPCOMING_INDICATOR_ERROR, userIdCode.getValue(), lackName, lackNum);
            }
            boolean sendResult = smsBizService.starUpcomingNotice(mobile,lackNum,lackName);
            if (!sendResult) {
                log.error("即将晋升短信异常，用户：{} ，mobile:{} 短信推送失败", userIdCode.getValue(), mobile);
                throw ApplicationException.error(UPCOMING_SMS_ERROR, userIdCode.getValue(), mobile);
            }
        } catch (Exception e) {
            log.info("即将晋升短信异常，推送记录回滚。idCode:{}", userIdCode.getValue());
            smsRecordRepository.rollbackRecord(userIdCode.getValue(), SmsKey.UPCOMING_NOTICE);
            throw e;
        }
    }
}
